package com.smile.frame.api.demo.base.config;

import com.smile.frame.api.demo.base.interceptor.AuthInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 认证拦截器
 *
 * @author LGC
 * @date 2021/9/2 15:05
 */
@Configuration
public class AuthInterceptConfiguration implements WebMvcConfigurer {

    @Resource
    private AuthInterceptor authInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 不拦截路径
        List<String> paths = new ArrayList<>();
        // 开放knife4j
        paths.add("/doc.html");
        paths.add("/favicon.ico");
        paths.add("/webjars/**");
        paths.add("/service-worker.js");
        paths.add("/swagger-resource/**");
        paths.add("/v2/api-docs/**");
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(paths);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置拦截器访问静态资源
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 允许全部请求跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //允许全部请求跨域
        CorsRegistration corsRegistration = registry.addMapping("/**");
        corsRegistration.allowedOrigins("*");
        corsRegistration.allowedHeaders("*");
        corsRegistration.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS");
        corsRegistration.allowCredentials(false).maxAge(3600);
    }

}
